import { thyReq, initImplements, UITypes, thyCookie, thyUrl } from '@thyiad/util';
import { LOGIN_COOKIE_KEY, REQUEST_HEADER_TOKEN_NAME, ROUTER_TYPE } from '../constants';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { RouteProps } from '@/router';

/**
 * 顶部加载中提示，返回实例的close方法关闭弹窗
 * @param msg 提示内容
 */
const msgLoading = (msg: string) => {
    return ElLoading.service({
        text: msg,
    });
};

/**
 * toast消息
 * @param msg 需要toast的消息内容
 * @param type 类型：success, warning, error, info，默认success
 */
const toast = (msg: string, type: UITypes = UITypes.success) => {
    ElMessage[type](msg);
};

/**
 * alert 消息框
 * @param msg alert 的 消息内容
 * @param type 类型：info, success, warning, error，默认 info
 * @param content 弹窗内容
 * @param cb 确认回调
 */
const alert = (msg: string, type: UITypes = UITypes.success, content = '', cb?: () => void) => {
    ElMessageBox.alert(msg, {
        title: '',
        confirmButtonText: '确定',
        callback: (action: string) => {
            if (action === 'confirm') {
                cb && cb();
            }
        },
    });
};

/**
 * 确认弹窗
 * @param msg 提示消息
 * @param ok 确认回调
 * @param cancel 取消回调
 */
const confirm = (msg: string, ok?: () => void, cancel?: () => void, content?: string) => {
    ElMessageBox.confirm(msg, {
        title: '',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
    })
        .then(() => {
            ok && ok();
        })
        .catch(() => {
            cancel && cancel();
        });
};

export const logout = () => {
    thyCookie.remove(LOGIN_COOKIE_KEY, { domain: thyUrl.getBaseHost() });
    if (ROUTER_TYPE === 'hash') {
        const idx = window.location.href.indexOf('#');
        const base = window.location.href.slice(0, idx);
        window.location.href = `${base}#/user/login`;
    } else if (ROUTER_TYPE === 'history') {
        window.location.href = `${window.location.origin}/user/login`;
    }
};

export const initThyiadUtils = () => {
    initImplements({
        ui: {
            msgLoading,
            toast,
            alert,
            confirm,
        },
        req: {
            loginCookeyKey: LOGIN_COOKIE_KEY,
            tokenHeaderName: REQUEST_HEADER_TOKEN_NAME,
            ajaxStatus: {
                success: 2000,
                error: 3000,
                expired: 4000,
            },
            ajaxData: {
                code: 'code',
                msg: 'msg',
                data: 'data',
            },
            logout,
        },
    });
};

export const getMatchRoute = (routeList: RouteProps[], path: string): RouteProps | null => {
    let findedRoute: RouteProps | null = null;

    for (let i = 0; i < routeList.length; i++) {
        const route = routeList[i];
        if (route.path === path) {
            findedRoute = route;
            break;
        }
        if (route.children && path.startsWith(route.path)) {
            findedRoute = getMatchRoute(route.children, path);
        }
        if (findedRoute) {
            break;
        }
    }

    return findedRoute;
};
